package com.ycg.biquge.schedule;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author YCG
 * @date 2024-05-16 14:37
 * @description 每天清理缓存
 */
@Component("cacheSchedule")
public class CacheSchedule {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 每天凌晨5点执行
     */
    @Scheduled(cron = "0 0 5 * * ?")
    public void clearCache() {
        Set<String> keys = stringRedisTemplate.keys("biquge:*");
        if (ObjectUtil.isNull(keys) || (ObjectUtil.isNotNull(keys) && keys.size() == 0)) return;
        for (String key : keys) {
            stringRedisTemplate.expire(key, RandomUtil.randomInt(1,10), TimeUnit.MINUTES);
        }
    }
}
